<template>
  <!-- 交接班处理 -->
  <view class="shift-deal-container">
    <!-- 基本信息 -->
    <BaseInfo :detail="detail" />

    <view :class="!editable ? 'form-container' : 'form-container uneditable'">
      <uni-forms ref="form" :modelValue="formData" :rules="editable ? rules : null" labelPosition="top">
        <view class="hidden-title">接班生产情况</view>
        <view class="background-white">
          <uni-forms-item name="takeoverProductionStatus" label="接班生产情况">
            <textarea
              v-if="editable"
              v-model="formData.takeoverProductionStatus"
              class="text-area"
              placeholder="请输入"
              placeholder-class="form-placeholder__style"
              maxlength="500"
            />
            <view v-else class="color-666666">{{ detail.takeoverProductionStatus }}</view>
          </uni-forms-item>
        </view>

        <!-- 巡检情况 -->
        <view class="hidden-title">巡检情况</view>
        <view class="background-white">
          <view class="row">
            <view class="color-666666">
              {{ `正常：${normalPollingListCount}项` }}
            </view>
            <view class="color-666666">
              {{ `异常：${abnormalPollingListCount}项` }}
            </view>
            <view class="color-A14430" @click="checkPollingList"> 详情 </view>
          </view>
        </view>
        <view class="line"></view>
        <!-- <InspectSituation :data="(editable ? formData.pollingList : detail.pollingList) || []" /> -->

        <!-- <view class="hidden-title">其他情况</view> -->
        <view class="background-white bor-bottom">
          <uni-forms-item name="technologyStatus" label="工艺情况">
            <textarea
              v-if="editable"
              v-model="formData.technologyStatus"
              class="text-area"
              placeholder="请输入"
              placeholder-class="form-placeholder__style"
              maxlength="500"
            />
            <view v-else class="color-666666">{{ detail.technologyStatus }}</view>
          </uni-forms-item>
        </view>
        <view class="line"></view>
        <view class="background-white">
          <uni-forms-item name="equipmentStatus" label="设备情况">
            <textarea
              v-if="editable"
              v-model="formData.equipmentStatus"
              class="text-area"
              placeholder="请输入"
              placeholder-class="form-placeholder__style"
              maxlength="500"
            />
            <view v-else class="color-666666">{{ detail.equipmentStatus }}</view>
          </uni-forms-item>
        </view>
        <view class="line"></view>
        <view class="background-white">
          <uni-forms-item name="handoverProductionStatus" label="交接生产情况">
            <textarea
              v-if="editable"
              v-model="formData.handoverProductionStatus"
              class="text-area"
              placeholder="请输入"
              placeholder-class="form-placeholder__style"
              maxlength="500"
            />
            <view v-else class="color-666666">{{ detail.handoverProductionStatus }}</view>
          </uni-forms-item>
        </view>

        <view class="hidden-title">安全生产情况</view>
        <cu-cell-group>
          <uni-forms-item name="hasHiddenDanger">
            <cu-cell title="隐患情况" :required="editable">
              <view class="flex flex-end">
                <CuRadioGroup
                  v-if="editable"
                  v-model="formData.hasHiddenDanger"
                  :list="yesOrNoDict"
                  @change="hasHiddenDangerInput"
                />
                <view v-else class="color-666666">{{ detail.hasHiddenDanger == 1 ? '有' : '无' }}</view>
              </view>
            </cu-cell>
          </uni-forms-item>
        </cu-cell-group>
        <!-- <view class="line"></view> -->
        <view class="background-white">
          <view class="row">
            <view class="color-666666">
              {{ `${hiddenDangerCount}项` }}
            </view>
            <view class="color-A14430" @click="checkHiddenDanger">
              {{ editable ? '核验' : '详情' }}
            </view>
          </view>
        </view>
        <!-- <HiddenDanger v-model="editable ? formData.hiddenDangerList : detail.hiddenDangerList"
					:editable="editable" /> -->

        <view class="gap"></view>
        <cu-cell-group>
          <uni-forms-item name="hasOverhaul">
            <cu-cell title="检修作业" :required="editable">
              <view class="flex flex-end">
                <CuRadioGroup
                  v-if="editable"
                  v-model="formData.hasOverhaul"
                  :list="yesOrNoDict"
                  @change="hasOverhaulInput"
                />
                <view v-else class="color-666666">{{ detail.hasOverhaul == 1 ? '有' : '无' }}</view>
              </view>
            </cu-cell>
          </uni-forms-item>
        </cu-cell-group>
        <!-- <view class="line"></view> -->
        <view class="background-white">
          <view class="row">
            <view class="color-666666">
              {{ `${overhaulCount}项` }}
            </view>
            <view class="color-A14430" @click="checkOverhaulList">
              {{ editable ? '核验' : '详情' }}
            </view>
          </view>
        </view>
        <!-- <Overhaul v-model="editable ? formData.overhaulList : detail.overhaulList" :editable="editable" /> -->

        <view class="gap"></view>
        <view class="background-white bor-bottom">
          <uni-forms-item name="dangerousChemicalStatus" label="危化品运行情况">
            <textarea
              v-if="editable"
              v-model="formData.dangerousChemicalStatus"
              class="text-area"
              placeholder="请输入"
              placeholder-class="form-placeholder__style"
              maxlength="50"
              style="height: 60px"
            />
            <view v-else class="color-666666">{{ detail.dangerousChemicalStatus }}</view>
          </uni-forms-item>
        </view>
        <view class="line"></view>

        <view class="background-white bor-bottom">
          <uni-forms-item name="personnelUnusualStatus" label="人员异常情况">
            <textarea
              v-if="editable"
              v-model="formData.personnelUnusualStatus"
              class="text-area"
              placeholder="请输入"
              placeholder-class="form-placeholder__style"
              maxlength="50"
              style="height: 60px"
            />
            <view v-else class="color-666666">{{ detail.personnelUnusualStatus }}</view>
          </uni-forms-item>
        </view>
        <view class="line"></view>

        <view class="background-white bor-bottom">
          <uni-forms-item name="environmentalStatus" label="环保">
            <textarea
              v-if="editable"
              v-model="formData.environmentalStatus"
              class="text-area"
              placeholder="请输入"
              placeholder-class="form-placeholder__style"
              maxlength="50"
              style="height: 60px"
            />
            <view v-else class="color-666666">{{ detail.environmentalStatus }}</view>
          </uni-forms-item>
        </view>
        <view class="line"></view>

        <view class="background-white bor-bottom">
          <uni-forms-item name="illegalStatus" label="“三违”情况">
            <textarea
              v-if="editable"
              v-model="formData.illegalStatus"
              class="text-area"
              placeholder="请输入"
              placeholder-class="form-placeholder__style"
              maxlength="50"
              style="height: 60px"
            />
            <view v-else class="color-666666">{{ detail.illegalStatus }}</view>
          </uni-forms-item>
        </view>

        <view class="hidden-title">公用器材及工具</view>
        <cu-cell-group v-if="editable">
          <uni-forms-item
            v-for="(item, index) in formData.equipmentAndToolsReqList"
            :name="['equipmentAndToolsReqList', index, 'toolsStatus']"
            required
            :rules="[{ required: true, errorMessage: '必填项不能为空' }]"
            :key="index"
          >
            <cu-cell :title="item.toolsName" required>
              <view class="flex flex-end">
                <CuRadioGroup
                  v-model="item.toolsStatus"
                  :list="toolsStatus"
                  :props="{ value: 'dictValue', label: 'dictLabel' }"
                />
              </view>
            </cu-cell>
          </uni-forms-item>
        </cu-cell-group>
        <cu-cell-group v-else>
          <uni-forms-item v-for="(item, index) in detail.equipmentAndToolsReqList" :key="index">
            <cu-cell class="no-width-limit" :title="item.toolsName + ':'">
              <view class="flex">
                {{ getToolsStatus(item.toolsStatus) }}
              </view>
            </cu-cell>
          </uni-forms-item>
        </cu-cell-group>

        <!-- 	<template v-if="node == 14">
					<view class="hidden-title">接班</view>
					<cu-cell-group>
						<uni-forms-item name="successorUserId">
							<CuUserSelector label="接班人员" placeholder="选择人员" :required="true"
								v-model="formData.successorUserId" />
						</uni-forms-item>
					</cu-cell-group>
				</template> -->
      </uni-forms>

      <uni-forms v-if="node == 1 || node == 15" ref="form2" :modelValue="formData2" :rules="rules2" labelPosition="top">
        <view class="hidden-title">记录</view>
        <view class="background-white bor-bottom">
          <uni-forms-item name="record" label="问题记录">
            <textarea
              v-model="formData2.record"
              class="text-area"
              placeholder="请输入"
              placeholder-class="form-placeholder__style"
              maxlength="500"
            />
          </uni-forms-item>
        </view>
      </uni-forms>

      <uni-forms v-if="!node" labelPosition="top">
        <view class="hidden-title">记录</view>
        <view class="background-white bor-bottom">
          <uni-forms-item name="takeoverRecord" label="当班主操问题记录：">
            <view class="color-666666">
              {{ detail.takeoverRecord || '--' }}
            </view>
          </uni-forms-item>
          <uni-forms-item name="pollingRecord" label="当班巡检问题记录：">
            <view class="color-666666">
              {{ detail.pollingRecord || '--' }}
            </view>
          </uni-forms-item>
        </view>
      </uni-forms>

      <view class="submit" v-if="node == 1 || node == 14 || node == 15" @click="handleSubmit">完成 </view>
    </view>
  </view>
</template>

<script>
import CuCellGroup from '@/components/cu-cell/cu-cell-group.vue'
import CuCell from '@/components/cu-cell/cu-cell.vue'
import CuRadioGroup from '@/components/cu-radio-group/cu-radio-group.vue'
import CuUserSelector from '@/components/CuUserSelector/index.vue'
import BaseInfo from './BaseInfo.vue'
import InspectSituation from './InspectSituation.vue'
import HiddenDanger from './HiddenDanger.vue'
import Overhaul from './Overhaul.vue'
import {
  getChangeShiftInfo,
  getChangeShiftHiddenDangerList,
  getChangeOverhaulList,
  mainOperation,
  takeoverConfirm,
  pollingConfirm,
  getChangeShiftPollingList
} from '@/api/duty-basic/duty-shifting.js'
import { getDicts } from '@/api/system/dict.js'
import dayjs from 'dayjs'
export default {
  name: 'StepShiftsMainOperator',
  props: {
    editable: {
      type: Boolean,
      default: false
    }
  },
  computed: {
    hiddenDangerCount() {
      let list = this.editable ? this.formData.hiddenDangerList : this.detail.hiddenDangerList
      return list.length
    },
    overhaulCount() {
      let list = this.editable ? this.formData.overhaulList : this.detail.overhaulList
      return list.length
    },
    normalPollingListCount() {
      let list = this.editable ? this.formData.pollingList : this.detail.pollingList
      return list.filter((item) => item.workStatus !== '存在异常').length
    },
    abnormalPollingListCount() {
      let list = this.editable ? this.formData.pollingList : this.detail.pollingList
      return list.filter((item) => item.workStatus === '存在异常').length
    }
  },
  data() {
    return {
      id: undefined,
      node: undefined,
      taskId: undefined,
      detail: {
        pollingList: [],
        takeoverProductionStatus: undefined, // 接班生产情况
        technologyStatus: undefined, // 工艺情况
        equipmentStatus: undefined, // 设备情况
        handoverProductionStatus: undefined, // 交班生产情况
        hiddenDangerList: [], // 隐患情况
        hasHiddenDanger: undefined, // 有无隐患情况（1：有，0：无）
        hasOverhaul: undefined, // 是否有检修作业（0：无，1有）
        overhaulList: [], // 检修作业

        dangerousChemicalStatus: undefined, // 危险化学品情况
        personnelUnusualStatus: undefined, // 人员异常
        environmentalStatus: undefined, // 环保
        illegalStatus: undefined, // 三违情况
        equipmentAndToolsReqList: [], // 公用器材及工具
        successorUserId: undefined // 接班人员
      },
      formData: {
        pollingList: [],
        takeoverProductionStatus: undefined, // 接班生产情况
        technologyStatus: undefined, // 工艺情况
        equipmentStatus: undefined, // 设备情况
        handoverProductionStatus: undefined, // 交班生产情况
        hiddenDangerList: [], // 隐患情况
        hasHiddenDanger: undefined, // 有无隐患情况（1：有，0：无）
        hasOverhaul: undefined, // 是否有检修作业（0：无，1有）
        overhaulList: [], // 检修作业

        dangerousChemicalStatus: undefined, // 危险化学品情况
        personnelUnusualStatus: undefined, // 人员异常
        environmentalStatus: undefined, // 环保
        illegalStatus: undefined, // 三违情况
        equipmentAndToolsReqList: [], // 公用器材及工具
        successorUserId: undefined // 接班人员
      },
      yesOrNoDict: [
        {
          label: '是',
          value: 1
        },
        {
          label: '否',
          value: 0
        }
      ],
      rules: {
        takeoverProductionStatus: {
          rules: [
            {
              required: true,
              errorMessage: '接班生产情况不能为空'
            }
          ]
        },
        technologyStatus: {
          rules: [
            {
              required: true,
              errorMessage: '工艺情况不能为空'
            }
          ]
        },
        equipmentStatus: {
          rules: [
            {
              required: true,
              errorMessage: '设备情况不能为空'
            }
          ]
        },
        handoverProductionStatus: {
          rules: [
            {
              required: true,
              errorMessage: '交接生产情况不能为空'
            }
          ]
        },
        hasHiddenDanger: {
          rules: [
            {
              required: true,
              errorMessage: '隐患情况未选择'
            }
          ]
        },
        hasOverhaul: {
          rules: [
            {
              required: true,
              errorMessage: '检修作业未选择'
            }
          ]
        },
        dangerousChemicalStatus: {
          rules: [
            {
              required: true,
              errorMessage: '危化品运行情况不能为空'
            }
          ]
        },
        personnelUnusualStatus: {
          rules: [
            {
              required: true,
              errorMessage: '人员异常情况不能为空'
            }
          ]
        },
        environmentalStatus: {
          rules: [
            {
              required: true,
              errorMessage: '环保情况不能为空'
            }
          ]
        },
        illegalStatus: {
          rules: [
            {
              required: true,
              errorMessage: '“三违”情况不能为空'
            }
          ]
        },
        successorUserId: {
          rules: [
            {
              required: true,
              errorMessage: '接班人员不能为空'
            }
          ]
        }
      },
      toolData: [],
      toolsStatus: [],
      formData2: {
        record: undefined
      },
      rules2: {
        record: {
          rules: [
            {
              required: true,
              errorMessage: '问题记录不能为空'
            }
          ]
        }
      }
    }
  },
  components: {
    CuCellGroup,
    CuCell,
    CuRadioGroup,
    BaseInfo,
    InspectSituation,
    HiddenDanger,
    Overhaul,
    CuUserSelector
  },
  watch: {
    'detail.handoverClassId'(val) {
      if (val) {
        this.editable && this.getChangeShiftPollingList()
      }
    }
  },
  mounted() {
    let curPage = getCurrentPages()
    let query = curPage[curPage.length - 1].options
    this.id = query.id
    this.node = query.node
    this.taskId = query.taskId
    this.getToolData()
    this.getChangeShiftInfo()
  },
  methods: {
    getChangeShiftPollingList() {
      getChangeShiftPollingList(
        this.detail.handoverClassId,
        dayjs(this.detail.handoverTime).format('YYYY-MM-DD'),
        this.detail.handoverDeptId
      ).then((res) => {
        this.formData.pollingList = res.data
      })
    },
    getToolsStatus(status) {
      let data = this.toolsStatus.find((item) => {
        if (item.dictValue == status) {
          return item
        }
      })

      return data?.dictLabel || ''
    },
    async getToolData() {
      const { data: toolsList } = await getDicts('dtr_equipment_and_tools')
      const { data: toolsStatus } = await getDicts('dtr_tools_status')
      let arr = []
      toolsList.map((item) => {
        arr.push({
          toolsName: item.dictLabel,
          toolsStatus: undefined,
          toolsValue: item.dictValue
        })
      })
      this.toolsStatus = toolsStatus
      this.formData.equipmentAndToolsReqList = arr
    },
    getChangeShiftInfo() {
      getChangeShiftInfo(this.id).then((res) => {
        console.log(res)
        this.detail = res.data
      })
    },
    async hasHiddenDangerInput(obj) {
      if (obj.value == 1) {
        const res = await getChangeShiftHiddenDangerList(this.detail.handoverDeptId)
        this.formData.hiddenDangerList = res.data
      } else {
        this.formData.hiddenDangerList = []
      }
      this.hasHiddenDanger = obj.value
    },
    async hasOverhaulInput(obj) {
      if (obj.value == 1) {
        const res = await getChangeOverhaulList(this.detail.handoverDeptId)
        this.formData.overhaulList = res.data
      } else {
        this.formData.overhaulList = []
      }
      this.hasOverhaul = obj.value
    },

    async handleSubmit() {
      if (this.node == 14) {
        await this.$refs.form.validate()
        await this.submitModal()
        await mainOperation({
          ...this.formData,
          changeShiftInfoId: this.id,
          processTaskId: this.taskId
        })
      }

      if (this.node == 1) {
        await this.$refs.form2.validate()
        await this.submitModal()
        await takeoverConfirm({
          takeoverRecord: this.formData2.record,
          changeShiftInfoId: this.id,
          processTaskId: this.taskId
        })
      }
      if (this.node == 15) {
        await this.$refs.form2.validate()
        await this.submitModal()
        await pollingConfirm({
          pollingRecord: this.formData2.record,
          changeShiftInfoId: this.id,
          processTaskId: this.taskId
        })
      }

      uni.showToast({
        title: '提交成功！',
        icon: 'success'
      })
      setTimeout(() => {
        uni.navigateBack()
      }, 1000)
    },

    submitModal() {
      return new Promise((resolve) => {
        uni.showModal({
          content: '提交后，填写的内容将不可以修改，请确定填写无误后再提交',
          confirmText: '确定',
          success: async (res) => {
            if (res.confirm) {
              resolve(true)
            }
          }
        })
      })
    },
    checkPollingList() {
      let obj = this.editable ? this.formData.pollingList : this.detail.pollingList
      uni.navigateTo({
        url: '/pages/work/team-or-group/shifting-handle/components/PollingListDetail',
        success: function (res) {
          // 通过eventChannel向被打开页面传送数据
          res.eventChannel.emit('getPollingList', obj)
        }
      })
    },
    checkHiddenDanger() {
      let obj = this.editable ? this.formData.hiddenDangerList : this.detail.hiddenDangerList
      let editable = this.editable
      uni.navigateTo({
        url: '/pages/work/team-or-group/shifting-handle/components/HiddenDangerDetail',
        success: function (res) {
          // 通过eventChannel向被打开页面传送数据
          res.eventChannel.emit('getHiddenDangerList', {
            obj,
            editable
          })
        }
      })
    },
    checkOverhaulList() {
      let obj = this.editable ? this.formData.overhaulList : this.detail.overhaulList
      let editable = this.editable
      uni.navigateTo({
        url: '/pages/work/team-or-group/shifting-handle/components/OverhaulDetail',
        success: function (res) {
          // 通过eventChannel向被打开页面传送数据
          res.eventChannel.emit('getOverhaulList', {
            obj,
            editable
          })
        }
      })
    }
  },
  onReady() {
    // 需要在onReady中设置规则
    if (this.editable) {
      this.$refs.form.setRules(this.rules)
    }
  }
}
</script>

<style lang="scss" scoped>
.shift-deal-container {
  padding-bottom: 20vh;
}

::v-deep .is-direction-top .uni-forms-item__label {
  width: 100% !important;
}

::v-deep .cell-item__title {
  width: 196rpx !important;
}

.line {
  height: 1rpx;
  background-color: #d5d7e3;
  margin-left: 30rpx;
}

.gap {
  height: 20rpx;
  background-color: #f5f5f5;
}

.submit {
  width: 600rpx;
  height: 88rpx;
  background: #454a5e;
  border-radius: 50rpx 50rpx 50rpx 50rpx;
  opacity: 1;
  text-align: center;
  line-height: 88rpx;
  font-size: 36rpx;
  font-weight: 400;
  color: #ffffff;
  margin: 0 auto;
  margin-top: 70rpx;
  margin-bottom: 70rpx;
}

::v-deep .no-width-limit .cell-item__title {
  width: auto !important;
}

.color-666666 {
  color: #666666;
}

.row {
  display: flex;
  justify-content: space-between;
  margin-top: 20rpx;
  margin-bottom: 20rpx;
}
</style>
